package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class MinioController {
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.endpoint}")
    private String point;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString() + suffix;

        try {
            //创建Minio的连接对象
            MinioClient minioClient = getClient();
            // 检查存储桶是否已经存在
            boolean isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExists){
                // 创建一个名为 reggie 的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .object("img/"+fileName)
                    .bucket(bucketName)
                    .contentType(file.getContentType()) //image/jpeg    /text/html
                    .stream(file.getInputStream(),file.getSize(),-1).build();
            minioClient.putObject(objectArgs);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }catch (Exception e){
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        MinioClient minioClient = getClient();
        try {
            GetObjectResponse   objectResponse = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object("img/"+name)
                    .build());
            ServletOutputStream sos = response.getOutputStream();
            IOUtils.copy(objectResponse, sos);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 免费提供一个获取Minio连接的方法
     * 获取Minio连接
     * @return
     */
    private MinioClient getClient(){
        MinioClient minioClient =
                MinioClient.builder()
                        // 设置连接哪个monio服务器
                        .endpoint(point)
                        .credentials(accessKey,secretKey)
                        .build();
        return minioClient;
    }
}














